package com.hb.trade.server.project.section.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hb.core.pojo.center.au.dto.ZappUserDTO;
import com.hb.core.pojo.center.au.entity.User;
import com.hb.core.pojo.center.au.mapper.UserMapper;
import com.hb.core.pojo.enums.OfferWayEnum;
import com.hb.core.pojo.project.proj.dto.ProjectBaseInfo;
import com.hb.core.pojo.project.proj.entity.AbstractProject;
import com.hb.core.pojo.project.section.dto.BidSectionOfferDTO;
import com.hb.core.pojo.project.section.dto.BidSectionOfferDetailTotalDTO;
import com.hb.core.pojo.project.section.dto.BidSectionOfferListDTO;
import com.hb.core.pojo.project.section.dto.SectionOfferSearchDTO;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.core.pojo.project.section.entity.BidSectionOffer;
import com.hb.core.pojo.project.section.entity.BidSectionOfferDetail;
import com.hb.core.pojo.project.section.entity.OfferExtInfo;
import com.hb.trade.server.project.notice.service.NoticeService;
import com.hb.trade.server.project.proj.manager.AbstractProjectManager;
import com.hb.trade.server.project.proj.service.ProjectService;
import com.hb.trade.server.project.section.service.raw.BidSectionOfferDetailService;
import com.hb.trade.server.project.section.service.raw.BidSectionOfferService;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import com.hb.trade.server.project.section.service.raw.OfferExtInfoService;
import com.hb.trade.server.project.util.DigitToChineseUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.fzzn.core.model.enums.LogicEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.Enums;
import org.fzzn.core.util.MsgUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 供应商标段报价表 前端控制器
 *
 * @author zhaojk
 * @since 2021-09-18
 */
@RestController
public class BidSectionOfferController {

    protected final NoticeService noticeService;
    protected final ProjectService projectService;
    protected final BidSectionService bidSectionService;
    protected final BidSectionOfferService bidSectionOfferService;
    protected final BidSectionOfferDetailService bidSectionOfferDetailService;
    protected final OfferExtInfoService offerExtInfoService;


    public BidSectionOfferController(NoticeService noticeService,
                                     ProjectService projectService,
                                     BidSectionService bidSectionService,
                                     BidSectionOfferService bidSectionOfferService,
                                     BidSectionOfferDetailService bidSectionOfferDetailService,
                                     OfferExtInfoService offerExtInfoService

                                     ) {
        this.noticeService = noticeService;
        this.projectService = projectService;
        this.bidSectionService = bidSectionService;
        this.bidSectionOfferService = bidSectionOfferService;
        this.bidSectionOfferDetailService = bidSectionOfferDetailService;
        this.offerExtInfoService = offerExtInfoService;

    }

    /**
     * 报价信息供应商列表
     * 首次报价
     *
     * @return
     */
    @PostMapping("/bidSectionOffer/tenders")
    public Message<List<BidSectionOfferListDTO>> tenders(@RequestBody SectionOfferSearchDTO searchVO) {
        if (searchVO.getSectionId() == null) {
            return MsgUtil.fail("标段ID不能为空");
        }
        // 查询指定标段供应商报价信息
        QueryWrapper<BidSectionOffer> wrapper = BidSectionOffer.wrapper();
        List<Integer> offerOrderList = bidSectionOfferService.getOfferOrder(searchVO.getSectionId());
        //判断是否是请求最新轮次供应商报价
        if (searchVO.getType() != null && searchVO.getType().equals("4")) {
            offerOrderList.clear();
            offerOrderList.add(CollUtil.max(offerOrderList));
        }

        List<BidSectionOfferListDTO> offerListVoList = new ArrayList<>();
        if (offerOrderList.size() > 0) {
            for (Integer integer : offerOrderList) {
                BidSectionOfferListDTO bidSectionOfferListVo = new BidSectionOfferListDTO();
                bidSectionOfferListVo.setOfferOrder(integer);
                wrapper.eq("section_id", searchVO.getSectionId());
                wrapper.eq("offer_order", integer);
                if (StringUtils.isNotEmpty(searchVO.getOfferId())) {
                    wrapper.eq("offer_id", searchVO.getOfferId());
                }
                List<BidSectionOffer> bidSectionOfferList = bidSectionOfferService.list(wrapper);
                List<Long> sectionOfferIds = bidSectionOfferList.stream().map(BidSectionOffer::getId).collect(Collectors.toList());
                if (sectionOfferIds.size() > 0) {
                    List<BidSectionOfferDetailTotalDTO> bidSectionOfferDetailTotalVoList = bidSectionOfferDetailService.findStatInSectionIds(sectionOfferIds);
                    bidSectionOfferDetailTotalVoList = bidSectionOfferDetailTotalVoList.stream()
                            .sorted(Comparator.comparing(BidSectionOfferDetailTotalDTO::getRateTotalPrice)).collect(Collectors.toList());
                    bidSectionOfferListVo.setBidSectionOfferDetailTotalVoList(bidSectionOfferDetailTotalVoList);
                    offerListVoList.add(bidSectionOfferListVo);
                }
            }
        }
        return MsgUtil.success(offerListVoList);
    }

    /**
     * 供应商报价详情
     *
     * @param sectionOfferSearch
     * @return
     */
    @PostMapping("/bidSectionOffer/detail")
    public Message<List<BidSectionOfferListDTO>> detail(@RequestBody SectionOfferSearchDTO sectionOfferSearch) {
        if (sectionOfferSearch.getSectionId() == null) {
            return MsgUtil.fail("标段ID不能为空");
        }
        // 报价项列表(计划明细报价信息)
        List<BidSectionOfferListDTO> planInfos = bidSectionOfferService.listOfferByTender(sectionOfferSearch);
        return MsgUtil.success(planInfos);
    }

    /**
     * 供应商报价其他信息
     *
     * @param searchVO
     * @return
     */
    @PostMapping("/bidSectionOffer/offerExtInfo")
    public Message<OfferExtInfo> offerExtInfo(@RequestBody SectionOfferSearchDTO searchVO) {
        if (searchVO.getSectionId() == null) {
            return MsgUtil.fail("标段ID不能为空");
        }
        List<BidSectionOffer> offerList = bidSectionOfferService.getOfferList(searchVO);
        OfferExtInfo offerExtInfo = new OfferExtInfo();
        if (offerList.size() > 0) {
            BidSectionOffer bidSectionOffer = offerList.get(offerList.size() - 1);
            //TODO
//            offerExtInfo = offerExtInfoService.getById(bidSectionOffer.getExtInfoId());
        }
        return MsgUtil.success(offerExtInfo);
    }


    /**
     * 新增供应商报价
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/bidSectionOffer/saveOffer")
    public Message saveOffer(@RequestBody BidSectionOfferDTO sectionOfferDto) {
        //处理报价其他信息
        OfferExtInfo extInfo = sectionOfferDto.getExtInfo();
        boolean save = offerExtInfoService.save(extInfo);

        // 查询出最后一次的报价轮次
        Integer offerOrder = bidSectionOfferService.getLastOffer(sectionOfferDto.getOfferId(), sectionOfferDto.getSectionId());
        sectionOfferDto.setOfferOrder(offerOrder + 1);
        sectionOfferDto.setExtInfoId(extInfo.getId());
        bidSectionOfferService.save(sectionOfferDto);

        List<BidSectionOfferDetail> bidSectionOfferDetailList = sectionOfferDto.getBidSectionOfferDetailList();
        bidSectionOfferDetailList.forEach(bidSectionOfferDetail -> {
            bidSectionOfferDetail.setSectionOfferId(sectionOfferDto.getId());
        });
        boolean saveBatch = bidSectionOfferDetailService.saveBatch(bidSectionOfferDetailList);
        return MsgUtil.msg(save && saveBatch);
    }

    /**
     * 项目基本信息
     *
     * @param sectionId
     * @return
     */
    @GetMapping("/bidSectionOffer/projectBaseInfo")
    public Message<ProjectBaseInfo> projectBaseInfo(@RequestParam Long sectionId) {
        // 标段信息
        BidSection section = bidSectionService.getById(sectionId);
        if (section == null) {
            return MsgUtil.fail("没有标段信息");
        }

        AbstractProject project = projectService.getByPrimaryKey(section.getProjectId());
        if (project == null) {
            return MsgUtil.fail("未查询到项目信息");
        }

        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
        projectBaseInfo.setProjectCode(project.getProjectCode());
        projectBaseInfo.setProjectName(project.getProjectName());

        projectBaseInfo.setSectionCode(section.getSectionCode());
        projectBaseInfo.setSectionName(section.getSectionName());
        // 报价截止时间
        projectBaseInfo.setBidOpeningTime(section.getOpenBidTime());

        // 报价方式在项目表中
        AbstractProjectManager projectManager = project.to(AbstractProjectManager.class);
        Object offerWay = projectManager.get("offerWay");
        projectBaseInfo.setOfferWayName(Enums.nameOf(OfferWayEnum.class, offerWay));

        // 是否报所有报价项
        Object offerAllFlag = projectManager.get("offerAllFlag");
        projectBaseInfo.setOfferAllFlagName(Enums.nameOf(LogicEnum.class, offerAllFlag));

        projectBaseInfo.setUserId(project.getUserId());
        return MsgUtil.success(projectBaseInfo);
    }


    /**
     * Description: 供应商提交报价
     *
     * @param bidSectionOffer
     * @author: fengbin
     * @date: 2022/2/21 17:23
     * @return: java.lang.Boolean
     */
    @PostMapping("/bidSectionOffer/legalSubmit")
    public Message<String> legalSubmit(@RequestBody BidSectionOfferDTO bidSectionOffer) {
        Boolean aBoolean = bidSectionOfferService.legalSubmit(bidSectionOffer);
        String msg = aBoolean ? "提交成功" : "此轮报价已结束，请勿提交";
        return MsgUtil.success(msg);
    }


    /**
     * Description:  获取投标人报价列表
     *
     * @param offerId 投标人id
     * @param sectionId 开标标段id
     * @author: fengbin
     * @date: 2022/2/22 10:33
     * @return: java.util.List<com.hb.core.pojo.project.section.dto.BidSectionOfferDTO>
     */
    @GetMapping("/bidSectionOffer/listOfferInfosByOffId")
    public Message<List<BidSectionOfferDTO>> listOfferInfosByOffId(@RequestParam("offerId") Long offerId, @RequestParam("sectionId") Long sectionId) {
        List<BidSectionOfferDTO> bidSectionOfferDTOS = bidSectionOfferService.listOfferInfosByOffId(offerId, sectionId);
        return MsgUtil.success(bidSectionOfferDTOS);
    }


    /**
    * Description: 金额小写转大写
    * @author: fengbin
    * @date: 2022/2/23 13:18
    * @param digit
     @return: org.fzzn.core.model.msg.Message<java.lang.String>
    */
    @GetMapping("/DigitToChineseUtil/digitToChinese")
    public  Message<String> digitToChinese( @RequestParam("digit")  String digit){
        String digitValue = DigitToChineseUtil.digitToChinese(digit);
        return MsgUtil.success(digitValue);
    }
}
